package pay.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class BeanAndXMLTurn<T> {

	public void beanToXml(T t) throws JAXBException {
		JAXBContext context = JAXBContext.newInstance(t.getClass());
		Marshaller marshaller = context.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");//
		// 编码格式
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);//
		// 是否格式化生成的xml串
		marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);//
		// 是否省略xml头信息（<?xml version="1.0" encoding="gb2312" standalone="yes"?>）
		marshaller.marshal(t, System.out);
	}

	@SuppressWarnings("unchecked")
	public T XMLStringToBean(String xmlStr, T t) {
		// Returnsms ben = new Returnsms();
		try {
			JAXBContext context = JAXBContext.newInstance(t.getClass());
			Unmarshaller unmarshaller = context.createUnmarshaller();
			// unmarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

			return (T) unmarshaller.unmarshal(new StringReader(xmlStr));
		} catch (JAXBException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String getParams(Map<String, String> xmlMap, String beanName) {
		StringBuilder sb = new StringBuilder();
		sb.append("<?xml version='1.0' encoding='utf-8' standalone='yes'?>");
		sb.append("<" + beanName + ">");
		for (String key : xmlMap.keySet()) {
			sb.append("     <" + key + ">" + xmlMap.get(key) + "</" + key + ">");
		}
		sb.append("</" + beanName + ">");
		return sb.toString();		
	}

}

